<template>
  <div class="tool-page">
    <div class="tool-header">
      <h1>加密解密工具</h1>
      <p>支持AES和RSA加密算法，保护您的敏感信息</p>
    </div>
    
    <div class="encrypt-tool">
      
      
      <div class="algorithm-selector">
        <label for="algorithm">选择算法：</label>
        <select id="algorithm" v-model="algorithm" class="form-control">
          <option value="aes">AES</option>
          <option value="rsa">RSA</option>
        </select>
      </div>


      
      <!-- AES密钥设置 -->
      <div class="form-group" v-if="algorithm === 'aes'">
        <label for="key">AES密钥：</label>
        <input type="text" id="key" v-model="aesKey" class="form-control" placeholder="请输入AES密钥（16/24/32位）" />
      </div>
      
      <!-- RSA密钥设置 -->
      <div class="form-group" v-if="algorithm === 'rsa'">
        <div class="rsa-settings">
          <div class="key-length-selector">
            <label for="key-length">密钥长度：</label>
            <select id="key-length" v-model="rsaKeyLength" class="form-control">
              <option value="1024">1024位</option>
              <option value="2048">2048位</option>
              <option value="4096">4096位</option>
            </select>
          </div>
        </div>
        <div class="rsa-keys">
          <div class="key-row">
            <div class="key-group">
              <label for="public-key">公钥：</label>
              <textarea 
                id="public-key" 
                v-model="rsaPublicKey" 
                class="form-control key-textarea" 
                placeholder="请输入RSA公钥"
                rows="3"
              ></textarea>
            </div>
            <div class="key-group">
              <label for="private-key">私钥：</label>
              <textarea 
                id="private-key" 
                v-model="rsaPrivateKey" 
                class="form-control key-textarea" 
                placeholder="请输入RSA私钥"
                rows="3"
              ></textarea>
            </div>
          </div>
        </div>
        <div class="key-actions">
          <button @click="generateRSAKeys" class="btn secondary" :disabled="isGeneratingKeys">
            {{ isGeneratingKeys ? '生成中...' : '生成RSA密钥对' }}
          </button>
          <button @click="clearRSAKeys" class="btn danger">清空密钥</button>
        </div>
      </div>
      

      
    
      
      <div class="text-container">
        <!-- 左侧：明文/密文输入 -->
        <div class="text-panel left-panel">
          <label for="input-text">{{ mode === 'encrypt' ? '明文' : '密文' }}：</label>
          <textarea 
            id="input-text" 
            class="form-control" 
            v-model="inputText" 
            :placeholder="mode === 'encrypt' ? '请输入需要加密的文本' : '请输入需要解密的文本'"
          ></textarea>
        </div>
        
        <!-- 中间：按钮区域 -->
        <div class="arrow-container">
          
            <div class="mode-selector">
              <div class="radio-group">
                <label class="radio-label">
                  <input type="radio" v-model="mode" value="encrypt" class="radio-input" />
                  <span class="radio-text">加密</span>
                </label>
                <label class="radio-label">
                  <input type="radio" v-model="mode" value="decrypt" class="radio-input" />
                  <span class="radio-text">解密</span>
                </label>
              </div>
            </div>
          <div class="action-buttons">
            <button @click="processText" class="btn primary">
              {{ mode === 'encrypt' ? '加密' : '解密' }}
            </button>
            <button @click="clearText" class="btn danger">清空</button>
          </div>
        </div>
        
        <!-- 右侧：密文/明文输入 -->
        <div class="text-panel right-panel">
          <label for="output-text">{{ mode === 'encrypt' ? '密文' : '明文' }}：</label>
          <div class="output-container">
            <textarea 
              id="output-text" 
              class="form-control" 
              v-model="outputText" 
              :placeholder="mode === 'encrypt' ? '加密结果将显示在这里' : '请输入需要解密的密文'"
            ></textarea>
            <button @click="copyToClipboard" class="btn copy-btn">
              复制结果
            </button>
          </div>
        </div>
      </div>
      
      <div class="error-message" v-if="errorMessage">
        {{ errorMessage }}
      </div>
    </div>
  </div>
</template>

<script>
import CryptoJS from 'crypto-js';
import JSEncrypt from 'jsencrypt';

export default {
  name: 'Encrypt',
  data() {
    return {
      mode: 'encrypt',
      algorithm: 'aes',
      aesKey: '',
      rsaPublicKey: '',
      rsaPrivateKey: '',
      rsaKeyLength: '2048',
      inputText: '',
      outputText: '',
      errorMessage: '',
      isGeneratingKeys: false
    }
  },
  methods: {
    processText() {
      if (!this.inputText.trim()) {
        this.errorMessage = '请输入需要处理的文本';
        return;
      }
      
      this.errorMessage = '';
      
      try {
        if (this.mode === 'encrypt') {
          this.encrypt();
        } else {
          this.decrypt();
        }
      } catch (error) {
        this.errorMessage = `处理失败: ${error.message}`;
        this.outputText = '';
      }
    },
    encrypt() {
      switch (this.algorithm) {
        case 'aes':
          if (!this.aesKey) {
            throw new Error('AES加密需要提供密钥');
          }
          this.outputText = this.aesEncrypt(this.inputText, this.aesKey);
          break;
        case 'rsa':
          if (!this.rsaPublicKey) {
            throw new Error('RSA加密需要提供公钥');
          }
          this.outputText = this.rsaEncrypt(this.inputText, this.rsaPublicKey);
          break;
        default:
          throw new Error('不支持的加密算法');
      }
    },
    decrypt() {
      switch (this.algorithm) {
        case 'aes':
          if (!this.aesKey) {
            throw new Error('AES解密需要提供密钥');
          }
          this.outputText = this.aesDecrypt(this.inputText, this.aesKey);
          break;
        case 'rsa':
          if (!this.rsaPrivateKey) {
            throw new Error('RSA解密需要提供私钥');
          }
          this.outputText = this.rsaDecrypt(this.inputText, this.rsaPrivateKey);
          break;
        default:
          throw new Error('不支持的解密算法');
      }
    },
    clearText() {
      this.inputText = '';
      this.outputText = '';
      this.errorMessage = '';
    },
    copyToClipboard() {
      if (!this.outputText) return;
      
      navigator.clipboard.writeText(this.outputText)
        .then(() => {
          alert('已复制到剪贴板');
        })
        .catch(err => {
          console.error('无法复制到剪贴板:', err);
        });
    },
    // AES加密
    aesEncrypt(text, key) {
      // 使用crypto-js库进行真正的AES加密
      const encrypted = CryptoJS.AES.encrypt(text, key);
      return encrypted.toString();
    },
    
    // AES解密
    aesDecrypt(text, key) {
      // 使用crypto-js库进行真正的AES解密
      const decrypted = CryptoJS.AES.decrypt(text, key);
      return decrypted.toString(CryptoJS.enc.Utf8);
    },
    
    // RSA加密
    rsaEncrypt(text, publicKey) {
      // 检查公钥格式
      if (!publicKey || !publicKey.includes('-----BEGIN PUBLIC KEY-----')) {
        throw new Error('请提供有效的RSA公钥');
      }
      
      // 估算密钥长度并计算最大加密长度
      const keySize = this.estimateKeySize(publicKey);
      const maxLength = Math.floor(keySize / 8) - 11; // RSA最大加密长度公式
      
      // 检查文本长度（UTF-8编码后的字节长度）
      const textBytes = new TextEncoder().encode(text).length;
      
      if (textBytes > maxLength) {
        throw new Error(`RSA加密内容过长！当前内容长度：${textBytes}字节，最大支持：${maxLength}字节（基于${keySize}位密钥）`);
      }
      
      // 使用jsencrypt库进行真正的RSA加密
      const encrypt = new JSEncrypt();
      encrypt.setPublicKey(publicKey);
      const encrypted = encrypt.encrypt(text);
      
      if (!encrypted) {
        throw new Error('RSA加密失败，请检查公钥格式是否正确');
      }
      
      return encrypted;
    },
    
    // 估算RSA密钥长度
    estimateKeySize(publicKey) {
      try {
        // 从公钥中提取模数来估算密钥长度
        const keyLines = publicKey.split('\n');
        const base64Key = keyLines.slice(1, -2).join('');
        const keyBytes = atob(base64Key);
        
        // 模数通常在公钥的第二个ASN.1序列中
        // 这里简化处理，根据常见密钥长度进行估算
        if (publicKey.includes('2048')) return 2048;
        if (publicKey.includes('4096')) return 4096;
        if (publicKey.includes('1024')) return 1024;
        
        // 默认返回2048位（与生成密钥时保持一致）
        return 2048;
      } catch (error) {
        // 如果估算失败，返回默认值
        return 2048;
      }
    },
    
    // RSA解密
    rsaDecrypt(text, privateKey) {
      // 使用jsencrypt库进行真正的RSA解密
      const decrypt = new JSEncrypt();
      decrypt.setPrivateKey(privateKey);
      const decrypted = decrypt.decrypt(text);
      
      if (!decrypted) {
        throw new Error('RSA解密失败，请检查私钥格式是否正确');
      }
      
      return decrypted;
    },
    
    // 生成RSA密钥对
    async generateRSAKeys() {
      if (this.isGeneratingKeys) return;
      
      this.isGeneratingKeys = true;
      this.errorMessage = '正在生成RSA密钥对，请稍候...';
      
      try {
        // 使用setTimeout模拟异步操作，让用户看到加载状态
        await new Promise(resolve => setTimeout(resolve, 100));
        
        // 使用用户选择的密钥长度
        const keySize = parseInt(this.rsaKeyLength);
        const encrypt = new JSEncrypt({ default_key_size: keySize });
        
        // 生成密钥对
        encrypt.getKey();
        
        // 获取公钥和私钥
        this.rsaPublicKey = encrypt.getPublicKey();
        this.rsaPrivateKey = encrypt.getPrivateKey();
        
        this.errorMessage = `RSA ${keySize}位密钥对已生成成功！`;
      } catch (error) {
        this.errorMessage = '生成密钥对失败: ' + error.message;
      } finally {
        this.isGeneratingKeys = false;
      }
    },
    
    // 清空RSA密钥
    clearRSAKeys() {
      this.rsaPublicKey = '';
      this.rsaPrivateKey = '';
    }
  },
  watch: {
    algorithm(newVal) {
      this.outputText = '';
      this.errorMessage = '';
    },
    mode() {
      this.outputText = '';
      this.errorMessage = '';
    }
  }
}
</script>

<style scoped>
.encrypt-tool {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.mode-selector {
  display: flex;
  gap: 1rem;
  margin-bottom: 0.5rem;
}

.mode-btn {
  flex: 1;
  text-align: center;
}

.mode-btn.active {
  background-color: var(--secondary-color);
}

.algorithm-selector {
  margin-bottom: 0.5rem;
}

.text-container {
  display: flex;
  gap: 2rem;
  align-items: stretch;
  min-height: 400px;
}

.text-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 100%;
}

.text-panel label {
  font-weight: bold;
  margin-bottom: 0.5rem;
  color: var(--text-color);
}

.text-panel .form-control {
  flex: 1;
  min-height: 300px;
  resize: vertical;
}

.arrow-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 2rem;
  min-width: 120px;
}

.arrow-direction {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 0.5rem;
}

.arrow-icon {
  font-size: 2.5rem;
  font-weight: bold;
  color: var(--primary-color);
  animation: pulse 2s infinite;
}

.arrow-label {
  font-size: 1rem;
  font-weight: bold;
  color: var(--text-color);
  background-color: var(--secondary-color);
  padding: 0.25rem 0.75rem;
  border-radius: 20px;
}

.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 1rem;
  width: 100%;
}

.action-buttons .btn {
  width: 100%;
  padding: 0.75rem;
}

.output-container {
  position: relative;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.copy-btn {
  position: absolute;
  bottom: 0.5rem;
  right: 0.5rem;
  padding: 0.25rem 0.5rem;
  font-size: 0.8rem;
  background-color: rgba(52, 152, 219, 0.1);
  color: var(--primary-color);
  z-index: 10;
}

.copy-btn:hover {
  background-color: rgba(52, 152, 219, 0.2);
}

.error-message {
  color: var(--accent-color);
  padding: 0.5rem;
  background-color: rgba(231, 76, 60, 0.1);
  border-radius: 4px;
}

/* RSA 密钥布局样式 */
.rsa-settings {
  margin-bottom: 1rem;
}

.key-length-selector {
  margin-bottom: 1rem;
}

.rsa-keys {
  margin-bottom: 1rem;
}

.key-row {
  display: flex;
  gap: 1rem;
  align-items: stretch;
}

.key-group {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.key-group label {
  font-weight: bold;
  margin-bottom: 0.5rem;
  color: var(--text-color);
}

.key-textarea {
  flex: 1;
  min-height: 176px;
  resize: vertical;
  font-family: monospace;
  font-size: 0.9rem;
}

.key-actions {
  display: flex;
  gap: 0.5rem;
  justify-content: flex-start;
}

@keyframes pulse {
  0%, 100% {
    transform: scale(1);
    opacity: 1;
  }
  50% {
    transform: scale(1.1);
    opacity: 0.8;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .text-container {
    flex-direction: column;
    gap: 1rem;
  }
  
  .arrow-container {
    flex-direction: row;
    min-width: auto;
    gap: 1rem;
  }
  
  .arrow-direction {
    flex-direction: row;
  }
  
  .action-buttons {
    flex-direction: row;
  }
  
  /* RSA 密钥移动端响应式 */
  .key-row {
    flex-direction: column;
    gap: 1rem;
  }
  
  .key-group {
    flex: none;
  }
  
  .key-actions {
    flex-direction: column;
  }
  
  .key-actions .btn {
    width: 100%;
  }
}
</style>